/**
 * Created by leo on 5/27/16.
 */

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var request = require('request');

//var net = require('net');
var server = require('http').createServer(app);
var io = require('socket.io')(server);

app.use(bodyParser.json());

Genre = require('./models/genre');
Book = require('./models/book');
Device = require('./models/device');
Category = require('./models/category');
Room = require('./models/room');

// Connect to Mongoose
mongoose.connect('mongodb://localhost/bookstore');
var db = mongoose.connection;

app.get('/', function(req, res) {
    res.send('Please use /api/generate');
});

//******************* genres
app.get('/api/genres', function(req, res) {
    Genre.getGenres(function(err, genres) {
        if (err) {
            throw err;
        }
        res.json(genres);
    });
});

app.post('/api/genres', function(req, res) {
    var genre = req.body;
    Genre.addGenre(genre, function(err, genre) {
        if (err) {
            throw err;
        }
        res.json(genre);
    });
});

app.put('/api/genres/:_id', function (req, res) {
    var id = req.params._id;
    var genre = req.body;
    Genre.updateGenre(id, genre, {}, function(err, genre) {
        if (err) {
            throw err;
        }
        res.json(genre);
    });
});

app.delete('/api/genres/:_id', function (req, res) {
    var id = req.params._id;
    Genre.removeGenre(id, function (err, genre) {
        if (err) {
            throw err;
        }
        res.json(genre);
    });
});


//******************* books
app.get('/api/books', function(req, res) {
    Book.getBooks(function(err, books) {
        if (err) {
            throw err;
        }
        res.json(books);
    });
});


app.get('/api/book/:_id', function(req, res) {
    Book.getBookById(req.params._id, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    });
});

app.post('/api/books', function(req, res) {
    var book = req.body;
    Book.addBook(book, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    });
});

app.put('/api/books/:_id', function (req, res) {
    var id = req.params._id;
    var book = req.body;
    Book.updateBook(id, book, {}, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    })
});

app.delete('/api/books/:_id', function (req, res) {
    var id = req.params._id;
    Book.removeBook(id, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    });
});


//******************* device
app.use('/api/devices', require('./routes/devices'));

//******************* Category
app.use('/api/categories', require('./routes/categories'));

//******************* room
app.use('/api/rooms', require('./routes/rooms'));


//******************* io
app.get('/socket', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
    console.log('one user connected ' + socket.id);
    socket.on('message', function (data) {
        var sockets = io.sockets.sockets;
        //sockets.forEach(function(sock){
        // if(sock.id != socket.id)
        // {
        //     console.log('ok');
        // sock.emit('message',data);
        // }
        // });
        socket.broadcast.emit('message', data);
    });
    socket.on('disconnect', function () {
        console.log('one user disconnected ' + socket.id);
    });
});

server.listen(1337);

//******************* nodejs-tcp


//var server = net.createServer(function (socket) {
//    socket.on('data', function (data) {
//        if (data === '123') {
//            socket.write('123');
//        } else {
//            socket.write('server reply ' + data);
//        }
//
//    });
//}).listen(1337, '127.0.0.1');

//var server = net.createServer(function(socket) {
//    socket.write('Echo server\r\n');
//    socket.pipe(socket);
//    socket.on('error', function(err) {
//        console.log(err);
//    });
//});
//
//server.listen(1337, '127.0.0.1');



//******************* send notice to android
app.post('/api/device/:_id/:_command', function (req, res) {
    var options = {
        url: 'https://api.bmob.cn/1/push',
        method: 'POST',
        json: true,
        headers: {
            'X-Bmob-Application-Id': '68b1340c9b81500e3fd31f1d14586dc7',
            'X-Bmob-REST-API-Key': '174730808c50dd82c4bb6c73d24ce639',
            'Content-Type': 'application/json'
        },
        body: {
            "where":{
                "deviceToken":"893fc04c73a966c1f0b69ca4a30ff75f62e9fd95c10b740e4335fa5ae0d0ce1a"
            },
            "data": {
                "aps":{"alert":JSON.stringify({
                    "id": req.params._id,
                    "command": req.params._command
                }),"badge":1,"sound":"default"}
            }
        }
    };
    request(options, function (err, response, body) {
        if (!err) {
            console.log('ok');
            res.json(body);
        }
    });
});

app.listen(3000);
console.log('Running on port 3000...');

